<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="区域/电表" prop="id" > 
        <region-ammeter-select
          v-model="queryParams.id"
          @change="handleNodeChange"
          style="width: 300px;"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker
          v-model="timeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bm:ammeterData:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ammeterDataList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id"  width="80" />
      <!-- <el-table-column label="厂区ID" align="center" prop="monitorId" />
      <el-table-column label="电表ID" align="center" prop="ammeterId" /> -->
      <el-table-column label="公司名称" align="center" prop="companyName" />
      <el-table-column label="厂区名称" align="center" prop="monitorName" />
      <el-table-column label="电表名称" align="center" prop="ammeterName" />
      <el-table-column label="正向有功电量" align="center" prop="electricityPae" />
      <el-table-column label="发生日期" align="center" prop="recordDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bm:ammeterData:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bm:ammeterData:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改电表数据对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="电表" prop="monitorId">
          <el-cascader
            v-model="selectedAmmeter"
            :options="treeData"
            :props="cascaderProps"
            @change="handleDialogNodeChange"
          />
        </el-form-item>
        <el-form-item label="时间" prop="recordDate">
          <el-date-picker
            v-model="form.recordDate"
            type="datetime"
            placeholder="选择时间"
            value-format="yyyy-MM-dd HH:mm:ss"
          />
        </el-form-item>
        <el-form-item label="正向有功电量" prop="electricityPae">
          <el-input v-model="form.electricityPae" placeholder="请输入正向有功电量" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listAmmeterData, getAmmeterData, delAmmeterData, addAmmeterData, updateAmmeterData } from "@/api/mes/bm/ammeterData";
import { getAmmeterTree } from "@/api/mes/bm/ammeter";
import RegionAmmeterSelect from "@/components/RegionAmmeterSelect";

export default {
  name: "AmmeterData",
  components: {
    RegionAmmeterSelect
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 电表数据表格数据
      ammeterDataList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        id: null,
        type: null,
        beginTime: null,
        endTime: null
      },
      // 表单参数
      form: {
        monitorId: null,
        ammeterId: null,
        recordTime: null
      },
      // 添加selectedAmmeter用于存储级联选择器的值
      selectedAmmeter: [],
      // 表单校验
      rules: {
        monitorId: [
          { required: true, message: "新增时请选择电表", trigger: "blur" }
        ],        ammeterId: [
          { required: true, message: "电表ID不能为空", trigger: "blur" }
        ],        recordDate: [
          { required: true, message: "发生日期不能为空", trigger: "blur" }
        ],        electricityPae: [
          { required: true, message: "正向有功电量不能为空", trigger: "blur" }
        ],        createBy: [
          { required: true, message: "创建者不能为空", trigger: "blur" }
        ],        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],        isDelete: [
          { required: true, message: "删除标识不能为空", trigger: "blur" }
        ]      },
      // 添加树形数据相关配置
      treeData: [],
      // 表单级联选择器配置
      cascaderProps: {
        emitPath: true,
        expandTrigger: 'hover',
        value: 'id',
        label: 'name',
        children: 'children',
        disabled: (data) => {
          return data.type !== 'ammeter';
        }
      },
      timeRange: []
    };
  },
  watch: {
    timeRange(val) {
      if (!val || val.length === 0) {
        this.queryParams.beginTime = null;
        this.queryParams.endTime = null;
      }
    }
  },
  created() {
    this.getList();
    this.getTreeData();
  },
  methods: {
    /** 查询电表数据列表 */
    getList() {
      this.loading = true;
      listAmmeterData(this.queryParams).then(response => {
        this.ammeterDataList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        
        monitorId: null,        
        ammeterId: null,        
        recordDate: null,        
        electricityPae: null,        
        createBy: null,        
        createTime: null,        
        updateBy: null,        
        updateTime: null,        
        remark: null,        
        isDelete: null      
      };
      this.resetForm("form");
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.timeRange = []; // 重置时间范围选择器
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        id: null,
        type: null,
        beginTime: null,
        endTime: null
      };
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      // 确保时间范围参数正确传递
      if (this.timeRange && this.timeRange.length === 2) {
        this.queryParams.beginTime = this.timeRange[0];
        this.queryParams.endTime = this.timeRange[1];
      }
      this.getList();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加电表数据";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getAmmeterData(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改电表数据";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 过滤掉null值
          const submitData = {};
          Object.keys(this.form).forEach(key => {
            if (this.form[key] !== null) {
              submitData[key] = this.form[key];
            }
          });

          if (this.form.id != null) {
            updateAmmeterData(submitData).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addAmmeterData(submitData).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除电表数据编号为"' + ids + '"的数据项？').then(function() {
        return delAmmeterData(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 获取树形数据 */
    getTreeData() {
      getAmmeterTree().then(response => {
        if (response.code === 200 && response.data) {
          this.treeData = this.formatTreeData(response.data);
        }
      });
    },
    /** 格式化树形数据 */
    formatTreeData(data) {
      // 如果数据为空，返回空数组
      if (!data || data.length === 0) {
        return [];
      }

      // 获取第一条数据中的psectorName作为根节点名称
      const rootName = data[0]?.bmMonitor?.psectorName || "北化浩绅";

      // 创建根节点
      const root = {
        id: '0', // 根节点ID设为'0'
        name: rootName,
        type: 'master',
        children: []
      };

      // 处理所有监控区域
      data.forEach(item => {
        if (item.bmMonitor) {
          const monitorNode = {
            id: item.bmMonitor.id,
            name: item.bmMonitor.name,
            type: 'slave',
            children: []
          };

          // 添加电表列表作为第三级节点
          if (item.bmAmmeterList && Array.isArray(item.bmAmmeterList)) {
            monitorNode.children = item.bmAmmeterList.map(ammeter => ({
              id: ammeter.id,
              name: ammeter.name,
              type: 'ammeter',
              monitorId: ammeter.monitorId
            }));
          }

          root.children.push(monitorNode);
        }
      });

      // 返回包含单个根节点的数组
      return [root];
    },
    /** 处理节点选择变化 */
    handleNodeChange({ id, type }) {
      this.queryParams.id = id;
      this.queryParams.type = type;
      this.handleQuery();
    },
    /** 处理弹窗中节点选择变化 */
    handleDialogNodeChange(value) {
      if (!value || value.length === 0) {
        this.form.monitorId = null;
        this.form.ammeterId = null;
      } else if (value.length === 3) {
        // 只允许选择电表级别
        this.form.monitorId = value[1];
        this.form.ammeterId = value[2];
      } else {
        // 如果不是电表级别，清空选择
        this.form.monitorId = null;
        this.form.ammeterId = null;
      }
    }
  }
};
</script>
